package com.example.demo.service;

import com.example.demo.config.WsSessionManager;
import io.micrometer.core.instrument.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

import java.net.URI;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * ws消息处理类
 */
@Slf4j
@Component
public class MyWsHandler extends AbstractWebSocketHandler {

    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        String query = Optional.of(session).map(WebSocketSession::getUri).map(URI::getQuery).orElse(null);
        Map<String, String> queryMap = this.getQueryMap(query);
        log.info("建立ws连接,queryMap={}", queryMap);
        WsSessionManager.add(session.getId(), session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String query = Optional.of(session).map(WebSocketSession::getUri).map(URI::getQuery).orElse(null);
        Map<String, String> queryMap = this.getQueryMap(query);
        log.info("接收到消息,queryMap={}", queryMap);
        // 获得客户端传来的消息
        String payload = message.getPayload();
        log.info("server 接收到消息 " + payload);
        session.sendMessage(new TextMessage("server 回复的消息 " + payload + "，发送时间:" + LocalDateTime.now()));
    }

    @Override
    protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) {
        log.info("发送二进制消息");
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) {
        log.error("异常处理");
        WsSessionManager.removeAndClose(session.getId());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        log.info("关闭ws连接");
        WsSessionManager.removeAndClose(session.getId());
    }

    private Map<String, String> getQueryMap(String query) {
        Map<String, String> map = new HashMap<>();
        if (StringUtils.isBlank(query)) return map;
        String[] querys = query.split("&");
        for (String parma : querys) {
            String[] parmas = parma.split("=");
            map.put(parmas[0], parmas[1]);
        }
        return map;
    }
}
